//
//  ClubMyselfInfoViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/18.
//

import UIKit
import ZLPhotoBrowser
import Photos

class ClubMyselfInfoViewController: ClubBaseViewController {
    
    private var topView = ClubMyselfInfoView()
    private var nameView = ClubMyselfInfoNickNameView()
    private var accountView = ClubMyselfInfoAccountView()
    private var birthdayView = ClubMyselfInfoBirthdayView()
    private var addressView = ClubMyselfInfoAddressView()
    private var delView = ClubMyselfInfoDelView()
    
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    
    private var userInfoM = ClubMineSelfModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            topView
            nameView
            accountView
            birthdayView
            addressView
            delView
        }

        topView.leading(0).trailing(0).top(0).height(220.0.Scale)
        nameView.leading(0).trailing(0).height(68.0.Scale)
        nameView.Top == topView.Bottom + 16.0.Scale
        accountView.leading(0).trailing(0).height(68.0.Scale)
        accountView.Top == nameView.Bottom + 16.0.Scale
        birthdayView.leading(0).trailing(0).height(68.0.Scale)
        birthdayView.Top == accountView.Bottom + 16.0.Scale
        addressView.leading(0).trailing(0).height(68.0.Scale)
        addressView.Top == birthdayView.Bottom + 16.0.Scale
        delView.leading(0).trailing(0).height(68.0.Scale)
        delView.Top == addressView.Bottom + 16.0.Scale
        
        topView.backBlock = {
            self.navigationController?.popViewController(animated: true)
        }
        topView.saveBlock = {
            self.updatePetName()
        }
        topView.iconBlock = {
            self.checkPhotoLibraryPermission()
        }
        birthdayView.isUserInteractionEnabled = true
        addressView.isUserInteractionEnabled = true
        delView.isUserInteractionEnabled = true
        let verfityTap = UITapGestureRecognizer(target: self, action: #selector(clickVerfityView))
        birthdayView.addGestureRecognizer(verfityTap)
        let addressTap = UITapGestureRecognizer(target: self, action: #selector(clickAddressView))
        addressView.addGestureRecognizer(addressTap)
        let delTap = UITapGestureRecognizer(target: self, action: #selector(clickDelView))
        delView.addGestureRecognizer(delTap)
    }
    

    private func loadData(){
        
        Task {
            let res = await network.request(.getUserInfo,type: ClubMineSelfModel.self)
            if res.isSuccess, let model = res.model {
                
                self.userInfoM = model
                self.topView.iconImageView.loadImage(url: model.face)
                self.nameView.nameTextField.text = model.pet_name
                self.accountView.valueLabel.text = model.user_name
                if model.birthday.count == 0 {
                    self.birthdayView.valueLabel.textColor = "#E57617".toColor
                    self.birthdayView.valueLabel.text = "完成实名认证后即可展示"
                    self.birthdayView.rightImageV.isHidden = false
                }else{
                    self.birthdayView.valueLabel.textColor = "#2E3033".toColor
                    self.birthdayView.valueLabel.text = model.birthday
                    self.birthdayView.rightImageV.isHidden = true
                }
            }
        }
    }
}


//MARK: action
extension ClubMyselfInfoViewController {
    
    private func updatePetName(){
        
        guard let petName = nameView.nameTextField.text, petName.count > 0 else { return }
        let dict = ["pet_name": petName]
        guard let jsonStr = ClubGlobalTool.shared.convertToJsonData(dict) else { return }
        guard let encryStr = ClubGlobalTool.shared.AES128Encrypt(plainText: jsonStr, key: "mtetbpryjhdxmnhx") else { return }
        ToastUtil.show()
        Task {
            let res = await network.request(.updateUserInfo(value: encryStr))
            ToastUtil.dismiss()
            if res.isSuccess {
                "修改成功".toast_success
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    private func updateUserIcon(iconImg: UIImage){
        
        RaeRequestParameterConfig.shared.uploadImage(uploadImage: iconImg) { urlString in
            
            let dict = ["face": urlString]
            guard let jsonStr = ClubGlobalTool.shared.convertToJsonData(dict) else { return }
            guard let encryStr = ClubGlobalTool.shared.AES128Encrypt(plainText: jsonStr, key: "mtetbpryjhdxmnhx") else { return }
            Task {
                _ = await self.network.request(.updateUserInfo(value: encryStr))

            }
        } failure: { errorMessage in
            
        }
        
        
    }
    
    private func checkPhotoLibraryPermission() {
         let status = PHPhotoLibrary.authorizationStatus()
             
         switch status {
             case .authorized:
                 // 已经授权，继续访问相册
             DispatchQueue.main.async {
                 self.showPhotoLibrary()
             }
                 
             case .denied, .restricted:
                 // 用户拒绝或受限，无法访问相册
                 print("用户拒绝访问相册")
             case .notDetermined:
                 // 用户还没有决定是否允许访问，进行请求
                 PHPhotoLibrary.requestAuthorization { newStatus in
                     if newStatus == .authorized {
                         // 用户授权，继续访问相册
                         DispatchQueue.main.async {
                             self.showPhotoLibrary()
                         }
                     } else {
                         print("用户拒绝访问相册")
                     }
                 }
         @unknown default:
                 print("未知的权限状态")
         }
     }
     
     private func showPhotoLibrary() {

         let config = ZLPhotoConfiguration.default()
         
         config.languageType = .chineseSimplified
         config.maxSelectCount = 1
         config.allowSelectGif = false
         config.allowMixSelect = false
         config.allowSelectVideo = false
         config.allowTakePhotoInLibrary = true
         config.allowEditVideo = false
         config.maxEditVideoTime = 30
         config.maxRecordDuration = 30
         config.editAfterSelectThumbnailImage = true
         config.allowSelectOriginal = false
         config.animateSelectBtnWhenSelect = false
         config.cropVideoAfterSelectThumbnail = true
         let ac = ZLPhotoPreviewSheet(selectedAssets:assets)
         
         ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
             self?.images = images
             self?.assets = assets
             self?.topView.iconImageView.image = images[0]
             self?.updateUserIcon(iconImg: images[0])
         }
         ac.showPhotoLibrary(sender: self)
     }
    
    @objc private func clickVerfityView(){
        
        if self.userInfoM.birthday.count == 0 {
            let verfityVC = ClubRealVerfityViewController()
            verfityVC.updateUserInfoData = {
                self.loadData()
            }
            self.navigationController?.pushViewController(verfityVC, animated: true)
        }
    }
    
    @objc private func clickAddressView(){
        
        self.navigationController?.pushViewController(ClubAddressListViewController(), animated: true)
    }
    
    @objc private func clickDelView(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=zhanwu&ac=userdelete&uid=" + uid + "&t=" + RaeRequestParameterConfig.shared.getTStr() + "&sign=" + RaeRequestParameterConfig.shared.encrySign()
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "账号注销"
            self.navigationController?.pushViewController(webView, animated: true)
        }
    }
}
